<template>
  <span>
    <el-dialog
      :visible.sync="visible"
      width="90%"
      center
      title="素材库管理"
      :z-index="100005"
      modal-append-to-body
      :close-on-click-modal="false"
      class="bg-white rounded-xl shadow-2xl transform transition-all duration-300"
    >
    <div class="flex-col" style="height: 700px;">
      <div class="flex-row overflow-auto p-5 bg-gray-50">
        <el-button type="primary" size="small" @click="addCrawlerLinkImg"
                   class="mt-4 px-4 py-2 rounded-lg shadow hover:shadow-md transition-all duration-200"
        >选择爬取任务的图</el-button>
        <el-button type="primary" size="small" @click="addImageStoreLinkImg"
                   class="mt-4 px-4 py-2 rounded-lg shadow hover:shadow-md transition-all duration-200"
        >选择图片库的图</el-button>
        <el-button type="primary" size="small" @click="uploadImg"
                   class="mt-4 px-4 py-2 rounded-lg shadow hover:shadow-md transition-all duration-200"
        >上传</el-button>
        <el-button type="danger" size="small" @click="confirmDeleteImageSelectAll"
                   class="mt-4 px-4 py-2 rounded-lg shadow hover:shadow-md transition-all duration-200"
        >删除</el-button>
      </div>
      <el-divider/>

      <el-tabs type="border-card"  v-model="statusType" class="flex-1 overflow-hidden flex-col" @tab-click="handleClick">
        <el-tab-pane :name="item.id" :label="item.text" v-for="(item,index) in statusArr" :key="index" class="fill-height flex-col">
          <div class="flex-1 overflow-auto">
            <el-row :gutter="24" style="margin: 0;">
              <el-col :span="24" :md="4" :lg="3" v-for="item in dataList" :key="item.id" style="padding: 6px;">
                <el-card class="thumbnail-card flex-col" @click.native.prevent="handleThumbnailSelect(item)" style="height: 220px;">
                  <template #header>
                    <div class="flex-row">
                      <el-checkbox v-model="item.selected"></el-checkbox>
                      <div class="flex-1"></div>
                      <div class="flex-row" style="gap: 10px">
                        <el-button type="text" text @click="confirmDeleteImage(item.id)" style="color: red;"
                        >删除</el-button>
                      </div>
                    </div>
                  </template>
                  <div class="fill-width-height flex-col flex-1 " style="min-height: 0;">
                      <LazyLoadImage
                        class="image"
                        fit="contain"
                        :src="item.url"
                        :lazy="true"
                      >
                      </LazyLoadImage>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>

      <div style="padding: 10px;">
         <el-divider/>
         <div class="flex-row">
          <span>全选/反选：</span>
          <el-checkbox v-model="selectedAll" @change="selectedAllChange"></el-checkbox>
        </div>
         <pagination
           :total="total"
           :page-sizes="[100, 200, 300, 500]"
           :page.sync="queryParams.pageNum"
           :limit.sync="queryParams.pageSize"
           @pagination="getPage"
           style="margin: 0!important; padding: 0!important; position: unset;"
         />
      </div>

      <div v-if="isShowConfirm">
        <el-divider/>
        <el-button type="primary" @click="confirm">确认</el-button>
      </div>
    </div>
  </el-dialog>

    <SelectCrawlerLinkImg ref="selectCrawlerLinkImgRef" @selectUrlsCallBack="selectUrlsCallBack"/>
    <SelectImgStoreImg ref="selectImgStoreImgRef" @selectUrlsCallBack="selectUrlsCallBack"/>
  </span>
</template>

<script>
import { deleteTobeImgByIds, saveTobeImgList, tobeImgPage, upload as uploadImage } from '@/api/imgManage/writeArticles'
import LazyLoadImage from '@/components/LazyLoadImage/index.vue'

export default {
  name: '',
  components: {
    LazyLoadImage,
    SelectCrawlerLinkImg: () => import('./selectCrawlerLinkImg'),
    SelectImgStoreImg: () => import('./selectImgStoreImg')
  },
  props: {
    isShowConfirm: {
      type: Boolean,
      default: () => false
    }
  },
  data() {
    return {
      visible: false,
      selectedAll: false,
      dataList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 100
      },
      statusType: 'toBeSel',
      statusArr: [
        { id: 'toBeSel', text: '待选' },
        { id: 'selected', text: '已选' },
        { id: 'published', text: '已发布' }
      ],
    }
  },
  computed: {},
  methods: {
    init() {
      this.visible = true
      this.getPage()
    },
    handleClick(tab, event){
      this.queryParams.pageNum = 1
      this.getPage()
    },
    async getPage() {
      const res = await tobeImgPage({ ...this.queryParams, imgstatus: this.statusType })
      this.dataList = res.rows
      this.total = res.total
    },
    selectedAllChange(){
      this.$nextTick(() => {
        setTimeout(() => {
          this.dataList.forEach(item => this.$set(item,'selected',this.selectedAll))
        },50)
      })
    },
    confirm() {
      this.$emit('confirm', this.getSelectedData())
      this.visible = false
    },
    getSelectedData() {
      return this.dataList?.filter(item => item.selected)
    },
    addCrawlerLinkImg() {
      this.$refs.selectCrawlerLinkImgRef.init()
    },
    uploadImg() {
      const input = document.createElement('input')
      input.type = 'file'
      input.accept = 'image/*'
      input.multiple = true

      // 监听文件选择事件
      input.onchange = async (e) => {
        const files = e.target.files
        if (!files.length) return
        this.$modal.loading("正在上传图片，请稍候...");
        try {
          let count = 0
          for (const file of files) {
            const formData = new FormData()
            formData.append('file', file)
            const res = await uploadImage(formData)
            if (res?.url) {
              const newUrl = res.url.startsWith('http') ? res.url : this.$config.urlFormat(res.url, false)
              await this.submit([newUrl])
              count++;
            } else {
              this.$message({
                type: 'warning',
                message: `文件 ${file.name} 上传失败`
              })
            }
          }
          // 所有文件上传完成
          this.$message({
            type: 'success',
            message: `成功上传 ${count} 张图片`
          })
        } catch (error) {
          // 上传过程中发生错误
          console.error('图片上传错误:', error)
          this.$message({
            type: 'error',
            message: '图片上传失败，请重试'
          })
          this.$modal.closeLoading()
        } finally {
          // 关闭加载提示
          this.$modal.closeLoading()
        }
      }
      // 触发文件选择对话框
      input.click()
    },
    addImageStoreLinkImg() {
      this.$refs.selectImgStoreImgRef.open()
    },
    selectUrlsCallBack(selectUrls) {
      this.submit(selectUrls)
    },
    handleThumbnailSelect(item) {
      this.$set(item, 'selected', !item.selected)
    },
    confirmDeleteImageSelectAll(){
      const ids = this.dataList
        .filter(item => item.selected)
        .map(item => item.id)
        .join(',')
      this.confirmDeleteImage(ids)
    },
    async confirmDeleteImage(id) {
      this.$modal.confirm('是否确认删除这' + id.split(',').length +'条数据？').then(function() {
        return deleteTobeImgByIds({ ids: id })
      }).then(() => {
        this.getPage()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '删除失败'
        })
      })
    },
    async submit(selectUrls) {
      const submitList = selectUrls.map(url => {
        return {
          url: url,
          imgstatus: 'toBeSel'
        }
      })
      const res = saveTobeImgList(submitList)
      if (res.code == 200) {
        await this.getPage()
        this.$message({
          type: 'success',
          message: '成功'
        })
      }
    }
  },
  mounted() {

  }
}
</script>


<style scoped lang="scss">
.thumbnail-card{

}
</style>
